﻿using System;
using System.Collections.Generic;

namespace ET
{
	[MessageHandler]
	public class C2G_LoginGateHandler : AMRpcHandler<C2G_LoginGate, G2C_LoginGate>
	{
		protected override async ETTask Run(Session session, C2G_LoginGate request, G2C_LoginGate response, Action reply)
		{
			try
			{
				Scene scene = session.DomainScene();
				TUser user = scene.GetComponent<UserComponent>().Get(request.UserId);
				if (user != null)
				{
					using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Login, request.UserId))
					{
						if (user.UnitId != 0)
							//发送重复登陆消息，通知对方客户端下线
							await ActorLocationSenderComponent.Instance.Call(user.UnitId, new G2M_AgainLogin());
					}
				}
				
				string account = scene.GetComponent<GateSessionKeyComponent>().Get(request.Key);
				if (account == null)
				{
					response.Error = ErrorCode.ERR_ConnectGateKeyError;
					response.Message = "Gate key验证失败!";
					reply();
					return;
				}
				DBComponent db = session.Domain.GetComponent<DBComponent>();
				List<TUser> users = await db.Query<TUser>(x => x.Account == account);
				user = users[0];

				scene.GetComponent<GateSessionKeyComponent>().Remove(request.Key);

				Game.Scene.GetComponent<UserComponent>().Add(user);
				session.AddComponent<SessionUserComponent>().User = user;
				session.AddComponent<MailBoxComponent, MailboxType>(MailboxType.GateSession);
				session.AddComponent<HeartBeatComponent>();

				reply();
				await ETTask.CompletedTask;
			}
			catch (Exception e)
			{
				ReplyError(response,e,reply);
			}
		}
	}
}